import axios from "axios";
import Cookies from 'js-cookie';
const TokenKey = 'huanxin_token';
const TokenUnix = 'token_end_time';

export function getToken() {
    let end_token_time = Cookies.get(TokenUnix)
    let now_unix_time = Date.parse(new Date())
    if(now_unix_time > end_token_time || end_token_time === '' || end_token_time === undefined) {//token过期了
        setToken()//获取token并写入cookie
    }

    let tokenstr = Cookies.get(TokenKey)
    //console.log('tokenstr' + tokenstr)
    return tokenstr
}

export function setToken() {
    let end_token_time = Cookies.get(TokenUnix)
    let now_unix_time = Date.parse(new Date())
    if(now_unix_time > end_token_time || end_token_time === '' || end_token_time === undefined){//token过期了
        axios({
            method: 'post',
            url: 'https://a1.easemob.com/1138210906051608/demo/token',
            data: JSON.stringify({
                "grant_type": "client_credentials",
                "client_id": "YXA6c_97gAWNTGWAdoe5mgs7kg",
                "client_secret": "YXA6atrb2m-9NoNvvEGL7aykY3WLpfU"
            }),
            headers: {
                'Content-Type': 'application/json'
            },
            timeout: 10000
        }).then((res)=>{
            if(res.status == 200) {//正常返回
                let Token = res.data.access_token
                let expires_time = res.data.expires_in
                let unix_time_now = Date.parse(new Date())
                let token_end_time = unix_time_now + expires_time
                //console.log(Token)
                Cookies.set(TokenUnix, token_end_time)
                return Cookies.set(TokenKey, Token)
            }else{
                if(res.status == 401) {
                    console.log('Token过期了')
                }else if(res.status == 400){
                    console.log('client_id 或 client_secret 错误')
                }else if(res.status == 429 || res.status == 503){
                    console.log('接口被限流了')
                }else{
                    console.log('其它问题找客服')
                    console.log('错误代码：' + res.status)
                    console.log('错误类型：' + res.data.error)
                    console.log('错误描述：' + res.data.error_description)
                }
            }
        }).catch(function (error) {
            //console.log(error.data);//undefined，之前以为这样可以拿到错误信息
            console.log(error.response,'-------');//可以拿到后端返回的信息
        });
    }
}

export function removeToken() {
    Cookies.remove(TokenUnix)
    return Cookies.remove(TokenKey)
}
